import React, { useEffect, useRef, useState } from "react";
import {
  Modal,
  ModalContent,
  ModalHeader,
  ModalBody,
  ModalFooter,
  Button,
  useDisclosure,
  Input,
  Select,
  SelectItem,
  Textarea,
  Chip,
  Avatar,
} from "@nextui-org/react";
import { showToast } from "../toast";
import { useGlobalState, useHttp } from "@/hooks";
import { copyText } from "@/utils/copy";
import { User } from "@/entities/User";
import { CheckOutlined, TaskAltSharp } from "@mui/icons-material";

type Props = {
  size?:
    | "xs"
    | "sm"
    | "md"
    | "lg"
    | "xl"
    | "2xl"
    | "3xl"
    | "4xl"
    | "5xl"
    | "full";
  openCallback?: Fn;
  closeCallback?: Fn;
  confirmCallback?: Fn;
  cancelBtnText?: string;
  confirmBtnText?: string;
  triggerBtnText?: string;
  mode: "create" | "edit";
  visible?: boolean;
  appId?: number;
  children?: React.ReactNode;
};

const UserModal: React.FC<Props> = ({
  size = "3xl",
  openCallback,
  closeCallback,
  triggerBtnText,
  confirmCallback,
  cancelBtnText,
  confirmBtnText,
  mode,
  appId,
  children,
  visible,
}) => {
  const { isOpen, onOpen, onClose } = useDisclosure();
  const isCreateMode = mode === "create";
  const [guests, setGuests] = useState<User[]>([]);
  const { isLoading, http } = useHttp();
  const [selections, setSelections] = useState(
    {} as { [key: string]: boolean }
  );

  const selectedCount = Object.values(selections).filter(
    (v) => v === true
  ).length;

  const handleSelect = (id: number) => {
    setSelections({ ...selections, [id]: !selections[id] });
  };

  useEffect(() => {
    if (visible) {
      handleOpenRef.current();
    }
  }, [visible]);

  const handleOpen = async () => {
    if (openCallback) {
      openCallback();
    }
    setSelections({});
    onOpen();
  };

  const handleOpenRef = useRef(handleOpen);
  handleOpenRef.current = handleOpen;

  const handleClose = () => {
    if (closeCallback) {
      closeCallback();
    }
    onClose();
  };

  const handleConfirm = async () => {
    const res = await http.post("/api/app/user/add", {
      appid: appId,
      userIds: Object.keys(selections).filter((id) => selections[id]),
    });

    if (confirmCallback) {
      setTimeout(() => {
        confirmCallback(res?.success);
      }, 1000);
    }

    handleClose();
  };

  useEffect(() => {
    if (!isOpen) return;

    const getGuestsOfApp = async () => {
      if (appId) {
        const res = await http.get("/api/app/user/guests", { appid: appId });
        if (res?.success) {
          setGuests(res.data.guests);
        }
      }
    };

    getGuestsOfApp();
  }, [isOpen, appId, http]);

  return (
    <div className="create-app-modal">
      {isCreateMode && (
        <Button size="sm" radius="md" color="primary" onClick={handleOpen}>
          {triggerBtnText || "Add"}
        </Button>
      )}
      <Modal size={size} isOpen={isOpen} onClose={handleClose}>
        <ModalContent>
          {(onClose) => (
            <>
              <ModalHeader className="flex flex-col gap-1">
                Add app user
              </ModalHeader>
              <ModalBody>
                <div className="app-guests">
                  {guests.map((guest) => (
                    <Chip
                      key={guest.id}
                      size="md"
                      className="m-4 cursor-pointer"
                      onClick={() => handleSelect(guest.id)}
                      startContent={
                        <Avatar
                          className="w-6 h-6"
                          name={guest.name}
                          src={guest.avatarData}
                        />
                      }
                      endContent={
                        selections[guest.id] ? (
                          <TaskAltSharp className="text-sm" />
                        ) : null
                      }
                      color={selections[guest.id] ? "success" : "default"}
                      variant="flat"
                    >
                      {guest.name}
                    </Chip>
                  ))}

                  {!isLoading && guests.length === 0 && (
                    <div className="text-center text-gray-300">
                      no other users
                    </div>
                  )}
                </div>
              </ModalBody>
              <ModalFooter>
                <Button
                  isLoading={isLoading}
                  color="primary"
                  isDisabled={selectedCount <= 0}
                  onClick={handleConfirm}
                >
                  {confirmBtnText || (isCreateMode ? "Create" : "Save")}
                </Button>

                {cancelBtnText && (
                  <Button color="primary" variant="flat" onPress={onClose}>
                    {cancelBtnText}
                  </Button>
                )}
              </ModalFooter>
            </>
          )}
        </ModalContent>
      </Modal>
    </div>
  );
};

export default UserModal;
